package department.fc.common;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Controller")
public class FrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		컨트롤러들의 공통적인 업무를 처리해주는 로직
		
		request.setCharacterEncoding("UTF-8");//전처리
		
		String command = request.getParameter("command");
		
		Controller controller = HandlerMapping.getController(command);
		
		try{
			AttributeAndView av = controller.handleRequest(request, response);
			if(av.isRedirect()){
				response.sendRedirect(av.getUrl());
			}else{
				Map<String, Object> attribute = av.getAttributes();
				if(attribute != null && attribute.size() != 0){
//					Set<Entry<String, Object>> entry = attribute.entrySet();
//					for(Entry<String, Object> e : entry){
//						request.setAttribute(e.getKey(), e.getValue());
						Set<String> keys = attribute.keySet();
						Iterator<String> itr = keys.iterator();
						while(itr.hasNext()){
							String key = itr.next();
							Object value = attribute.get(key);
							request.setAttribute(key, value);
					}
				}
				
				RequestDispatcher rdp = request.getRequestDispatcher(av.getUrl());
				rdp.forward(request, response);
			}
			
		}catch(Exception e){
			e.printStackTrace();
			throw new ServletException(e);
		}
	}

}
